package com.stetho.ai.a;

import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

import androidx.annotation.Nullable;

import com.stetho.ai.a.aidl.AIServiceInterface;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

public class AIService extends Service {

    private final String TAG = "AIService";

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return new AIServiceInterface.Stub() {
            @Override
            public void init() throws RemoteException {
                AI.getInstance().init();
            }

            @Override
            public String getResultByUri(Uri pcmUri) throws RemoteException {
                try {
                    Log.w(TAG, "getReuleByUri#uri=" + pcmUri);
                    // 1、将pcm写到缓存目录
                    InputStream inputStream = getContentResolver().openInputStream(pcmUri);
                    File tempPcm = new File(getCacheDir(), "temp.pcm");
                    if (tempPcm.exists()) {
                        tempPcm.delete();
                    }
                    OutputStream os = new FileOutputStream(tempPcm);

                    byte[] buffer = new byte[512];
                    int len;
                    while ((len = inputStream.read(buffer)) > 0) {
                        Log.i(TAG, "读取到数据。size=" + len);
                        os.write(buffer, 0, len);
                    }
                    os.close();
                    inputStream.close();

                    // 2、调用AI将pcm转成wav
                    File tempWav = new File(getCacheDir(), "temp.wav");
                    if (tempWav.exists()) {
                        tempWav.delete();
                    }
                    AI.getInstance().pcmToWav(tempPcm.getAbsolutePath(), tempWav.getAbsolutePath());

                    // 调用AI获取wav是否正常心音
                    return AI.getInstance().getResult(tempWav.getAbsolutePath());

                } catch (Exception e) {
                    RemoteException re = new RemoteException(e.getMessage());
                    re.setStackTrace(e.getStackTrace());
                    throw re;
                }
            }

        };
    }
}
